package com.bing.utils.utilstool;


import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * HttpClient工具类
 * Created by yanghe on 2018/8/10.
 */
public class HttpClientUtils {

    /**
     * HttpClient调用第三方接口 （POST）
     * @param url ：接口url
     * @param param ：接口参数
     * @return
     */
    public static Map<String,String> sendPurchaseReport(String url, Map<String,String> param){
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        Map<String,String> resultMap = new HashMap<>();

        try {
            httppost.addHeader("Content-type", "application/x-www-form-urlencoded");
            httppost.setEntity(prepareHttpEntity(param));

            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                //读返回数据
                String conResult = EntityUtils.toString(response.getEntity(),"gbk");
                resultMap.put("requsetState","true");
                resultMap.put("clob",conResult);
            } else {
                String err = response.getStatusLine().getStatusCode()+"";
                resultMap.put("requsetState","false");
                resultMap.put("clob",response.getStatusLine().getStatusCode()+"");
            }
        } catch (ClientProtocolException e) {
            resultMap.put("requsetState","false");
            resultMap.put("clob",e.toString());
            e.printStackTrace();
        } catch (ConnectTimeoutException e){
            resultMap.put("requsetState","false");
            resultMap.put("clob",e.toString());
            e.printStackTrace();
        }catch (IOException e) {
            resultMap.put("requsetState","false");
            resultMap.put("clob",e.toString());
            e.printStackTrace();
        } finally {
            //关闭连接 ,释放资源
            httpclient.getConnectionManager().shutdown();
        }
        return resultMap;
    }

    /**
     * HttpClient调用第三方接口 （GET）
     * @param url
     * @param param
     * @return
     */
    public static Map<String,String> sendGetRequest(String url,Map<String,Object> param){
        HttpClient client = HttpClients.createDefault();
        Map<String,String> resultMap = new HashMap<>();

        HttpGet get = new HttpGet(url+getUrlParamsByMap(param));
        try {
            HttpResponse response = client.execute(get);
            if(response.getStatusLine().getStatusCode() == 200){
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                resultMap.put("requsetState","true");
                resultMap.put("clob",result);
            }else{
                String err = response.getStatusLine().getStatusCode()+"";
                resultMap.put("requsetState","false");
                resultMap.put("clob",response.getStatusLine().getStatusCode()+"");
            }
        } catch (ClientProtocolException e) {
            resultMap.put("requsetState","false");
            resultMap.put("clob",e.toString());
            e.printStackTrace();
        } catch (ConnectTimeoutException e){
            resultMap.put("requsetState","false");
            resultMap.put("clob",e.toString());
            e.printStackTrace();
        }catch (IOException e) {
            resultMap.put("requsetState","false");
            resultMap.put("clob",e.toString());
            e.printStackTrace();
        } finally {
            //关闭连接 ,释放资源
            client.getConnectionManager().shutdown();
        }
        return resultMap;
    }

    /**
     * 利用Map结构的参数生成HttpEntity，使用UrlEncodedFormEntity对参数对进行编码
     * @param params
     * @return
     */
    private static HttpEntity prepareHttpEntity(Map<String, String> params) {
        // 需要将String里面的key value拆分出来
        HttpEntity requestHttpEntity = null;
        try {
            if (params != null) {
                List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(entry.getKey(),
                            entry.getValue());
                    pairList.add(pair);
                }
                requestHttpEntity = new UrlEncodedFormEntity(pairList,"UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return requestHttpEntity;
    }

    /**
     * 将map转换成url
     * @param map
     * @return
     */
    public static String getUrlParamsByMap(Map<String, Object> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer("?");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }

    /**
     * 将map转换成url
     * @param map
     * @return
     */
    public static String getUrlParamsByStringMap(Map<String, String> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }

    /**


    /**
     * 获取请求参数中所有的信息
     * 当商户上送frontUrl或backUrl地址中带有参数信息的时候，
     * 这种方式会将url地址中的参数读到map中，会导多出来这些信息从而致验签失败，这个时候可以自行修改过滤掉url中的参数或者使用getAllRequestParamStream方法。
     * @param request
     * @return
     */
    public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {

        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                // 在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
                if (res.get(en) == null || "".equals(res.get(en))) {
                    // System.out.println("======为空的字段名===="+en);
                    res.remove(en);
                }
            }
        }
        return res;
    }



}
